<?php
/**
 * Create a new Material
 */

use Fox\MaterialManagement\Material\Hierarchy;
use Fox\Html\TabPanel\Tab,Fox\Html\Screen,Fox\Html\Wrapper,Fox\Html\TabPanel;
use Fox\MaterialManagement\Material;

$hierarchyValue = $selectedNode = null;

$screen = new Fox\Html\Screen("eMaterial","create");
$tabPanel = new TabPanel("pMaterial");
$wMasterData = new Wrapper("wMasterData");
$blHeader = Xview::instance()->component("material", "header");
$blHeader->item("materialid")->hidden();
$wMasterData->add($blHeader);
// Hierarchy Part
$blHierarchy = Xview::instance()->component("material", "hierarchy");
if($screen->submitted())
{
	$hierarchyTree = $blHierarchy->item("hierarchyTree")->get(null,true);

	foreach($hierarchyTree as $node)
	{
		if($node['coche'] ===  't' || $node['coche'] ===  1)
		{
			$selectedNode[$node['level']][$node['code']] = 1;
			if(isset($levels[$node['level']]))
			{
				Fox\Message::Error(Msg(Material::BUNLDE_NAME,20));
			}
			$levels[$node['level']] = true;
			$hierarchyValue .= $node['code'];
		}
	}
}
$root = new Fox\Node(Fox\Node::ROOT_NODE);
$hiearchies = Hierarchy::loadTree();
foreach($hiearchies as $hierarchy)
{
	$parentid = $hierarchy['parentid'];
	if(!empty($parentid) && !isset($hiearchyTree[$parentid]))
		continue;

	if(isset($selectedNode[$hierarchy['level']][$hierarchy['code']]))
		$hierarchy['coche'] = 't';
	else
		$hierarchy['coche'] = 'f';
	if(empty($parentid))
		$hiearchyTree[$hierarchy['id']] = $root->add(new Fox\Node($hierarchy));
	else
		$hiearchyTree[$parentid]->add(new Fox\Node($hierarchy));
}
$blHierarchy->item("hierarchyTree")->initialize($root,true);
$wMasterData->add($blHierarchy);
$tabPanel->add(new Tab("tMasterData",Msg(Fox\Msg::BUNDLE,Fox\Msg::TITLE_MASTER_DATA),$wMasterData));
$screen->add($tabPanel);

if($screen->submitted())
{
	$inputs = $screen->get();
	//
	if(!$screen->errors())
	{
		try {

			// Convert Hiearchy into a string
			$inputs['hierarchy'] = $hierarchyValue;
			// Create Product
			$object = new Material();
			$object->setFields($inputs);
			$object->create();
			$id = $object->getId();
			Fox\Message::Success(Msg(Fox\Msg::BUNDLE,Fox\Msg::MSG_CREATE,$inputs['label']));
			Xview::instance()->redirect("?mod=material&act=update&materialid=$id");
		}
		catch(Fox\Object\Exception\Save $e)
		{
			Fox\Core\Errors::pushMessage($e);
		}
	}
}
echo '<h1>'.Msg(Material::BUNLDE_NAME,18).'</h1>';
echo $screen->Display();